package com.training.bt.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.training.bt.entity.PromotionResource;
import com.training.bt.mapper.PromotionResourceMapper;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class PromotionResourceService implements IPromotionResourceService {
    private final PromotionResourceMapper promotionResourceMapper;

    public PromotionResourceService(PromotionResourceMapper promotionResourceMapper) {
        this.promotionResourceMapper = promotionResourceMapper;
    }

    @Override
    public PromotionResource createPromotionResource(PromotionResource promotionResource) {
        // 检查重复关联
        LambdaQueryWrapper<PromotionResource> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PromotionResource::getPromotionId, promotionResource.getPromotionId())
                .eq(PromotionResource::getResourceId, promotionResource.getResourceId());
        PromotionResource existing = promotionResourceMapper.selectOne(wrapper);

        if (existing != null) {
            return existing;
        }

        promotionResourceMapper.insert(promotionResource);
        return promotionResource;
    }

    @Override
    public Optional<PromotionResource> getPromotionResourceById(Long relationId) {
        return Optional.ofNullable(promotionResourceMapper.selectById(relationId));
    }

    @Override
    public List<PromotionResource> getByPromotionId(Long promotionId) {
        return promotionResourceMapper.selectByPromotionId(promotionId);
    }

    @Override
    public List<PromotionResource> getByResourceId(Long resourceId) {
        return promotionResourceMapper.selectByResourceId(resourceId);
    }

    @Override
    public void deletePromotionResource(Long relationId) {
        promotionResourceMapper.deleteById(relationId);
    }

    @Override
    public void deleteByPromotionId(Long promotionId) {
        LambdaQueryWrapper<PromotionResource> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PromotionResource::getPromotionId, promotionId);
        promotionResourceMapper.delete(wrapper);
    }

    @Override
    public void deleteByResourceId(Long resourceId) {
        LambdaQueryWrapper<PromotionResource> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PromotionResource::getResourceId, resourceId);
        promotionResourceMapper.delete(wrapper);
    }

    @Override
    public double discount(Long resourceId) {
        return promotionResourceMapper.discount(resourceId);
    }

}